<?php
namespace Console\Map;

use Commons\Http;
use Commons\MobileControl\Car;
use Console\Config\Base;
use Redis;
use Swoole\Process;
use Swoole\WebSocket\Server as WebSocketServer;
use Commons\MobileControl\Car as KulalaCar;

class ServerTask extends Base
{
    /**
     * @var use Swoole\WebSocket\Server
     */
    private $server;
    /**
     * @var Event
     */
    private $event;
    /**
     * @var \Redis
     */
    private static $redis;
    /**
     * @var string 存储fd的队列
     */
    public static $connectionSet = 'ws';

    public function initialize()
    {
        $this->event = new Event();
    }

    public function mainAction()
    {
        $this->server = $server = new WebSocketServer('127.0.0.1', 9580, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
        $this->server->set([
            'worker_num' => 4,  //设置worker进程数
            'daemonize'  => false  //为true就为管道输出，false直接在屏幕显示
        ]);
        //创建子进程
        // $process = new Process(function (Process $worker) use ($server) {
        //     while(true) {
        //         $ret = $worker->read();
        //         var_dump($ret);
        //     }
        // });
        //        $this->server->addProcess($process);
        $this->server->on('WorkerStart', function (WebSocketServer $serv, $workerId)
        {
            if ($workerId == 0) {
                $serv->tick(30000, function () use ($serv)
                {
                    foreach ($serv->connections as $fd) {
                        $this->event->heartbeat($serv, $fd);
                    }
                });
            }
        });
        $this->server->on('open', function (WebSocketServer $serv, $request)
        {
            self::timerTick($serv, $request);
            swoole_timer_tick(10000, function () use ($serv, $request)
            {
                self::timerTick($serv, $request);
            });
        });
        $this->server->on('message', function (WebSocketServer $serv, $frame)
        {
            $data = json_decode($frame->data, true);
            if ($data['act'] == 'queryCarGps') {
            }
        });
        $this->server->on('close', function (WebSocketServer $serv, $fd)
        {
        });
        $this->server->start();
    }

    /**
     * @return \Redis
     * @throws \Exception
     */
    public static function redis()
    {
        if (is_null(self::$redis)) {
            self::$redis = new Redis();
            self::$redis->pconnect('127.0.0.1');
            return self::$redis;
        }
        try {
            if (self::$redis->ping() == '+PONG') {
                return self::$redis;
            } else {
                self::$redis = new Redis();
                self::$redis->pconnect('127.0.0.1');
                return self::$redis;
            }
        } catch (\Exception $ex) {
            throw new \Exception('链接缓存服务器失败');
        }
    }

    public static function isWebSocketClient($client, WebSocketServer $serv)
    {
        $info = $serv->getClientInfo($client);
        if ($info['websocket_status'] == \WEBSOCKET_STATUS_FRAME) {
            return true;
        }
        return false;
    }

    /**
     * @param WebSocketServer $serv
     * @param                 $frame
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function timerTick(WebSocketServer $serv, $frame)
    {
        $arr    = [
            'carIds' => '20486,22686,18620,21545,22034,22236,22654,21917,22677,21961,22686,19104,20486,19738,20486,19738,23903,20528,22725,22728,22749,22791,23032,23108'
        ];
        $car    = new Car();
        $result = $car->query($arr, 'kulala.api.car.status.list');
        $result = $result['carStatusInfos'];
        $list   = [];
        foreach ($result as $_k => $_v) {
            $path      = array_reverse(explode(',', $_v['gps']));
            $list[$_k] = [
                'path'    => implode(',', $path),
                'content' => '川A' . $_v['carId']
            ];
            if ($_v['isStart'] == 1 && $_v['isOnline'] == 1) {
                $color = 'green';
            } else {
                if ($_v['isStart'] == 0 && $_v['isOnline'] == 1) {
                    $color = 'red';
                } else {
                    $color = 'yellow';
                }
            }
            $list[$_k]['color'] = $color;
        }
        $baidu = self::gpsToBaiDuMap(array_column($list, 'path'));
        if (is_array($baidu) && count($baidu) > 0 && $baidu['status'] == 0) {
            foreach ($list as $k => $value) {
                $list[$k]['path'] = [
                    'lng' => $baidu['result'][$k]['x'],
                    'lat' => $baidu['result'][$k]['y']
                ];
            }
        }
        $serv->push($frame->fd, json_encode([
            'act'  => 'query',
            'list' => $list
        ]));
    }

    /**
     * Gps坐标转百度
     *
     * @param $arr
     *
     * @return mixed|\Psr\Http\Message\ResponseInterface|\Psr\Http\Message\StreamInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function gpsToBaiDuMap($arr)
    {
        $params = '';
        foreach ($arr as $_k => $_v) {
            $params = $params . trim($_v) . ';';
        }
        $params = rtrim($params, ';');
        $api    = 'http://api.map.baidu.com/geoconv/v1/?coords=%s&from=1&to=5&ak=NdmCgg96HrOdtXxjy5HGywWO11RSidTh';
        $api    = sprintf($api, $params);
        $result = Http::request($api);
        return $result;
    }

}
